<template>
    <div class="quiz-data-search">
        <div class="search">
            <div class="select" @click="showPicker = true">
                {{ retrieveFields == "name" ? "查标题" : "" }}
                {{ retrieveFields == "info_content_text" ? "查文章" : "" }}
                {{ retrieveFields == "push_number" ? "查文号" : "" }}
                {{ retrieveFields == "push_date" ? "查时间" : "" }}
                <van-icon
                    name="play"
                    size="0.8rem"
                    color="#333333"
                    class="select-icon"
                />
            </div>
            <div class="line"></div>
            <div class="input">
                <van-search
                    v-if="retrieveFields != 'push_date'"
                    v-model="searchInput"
                    placeholder="请输入搜索关键词"
                    @search="searchClick"
                />
                <div v-else class="input-date">
                    <div @click="showDatePopup(1)">{{ date1 }}</div>
                    <span>至</span>
                    <div @click="showDatePopup(2)">{{ date2 }}</div>
                </div>
            </div>
            <van-icon
                name="search"
                size="1.5rem"
                color="#333333"
                class="search-icon"
                @click="searchClick"
            />
        </div>

        <div class="data-list">
            <div class="total">为您找到约{{ total }}条信息</div>
            <nuxt-link
                v-for="(item, index) in pageDataList"
                :key="index"
                :to="`/kjfgk/${item.policyData.id}.html`"
                target="_blank"
                class="data-item"
            >
                <div class="title" v-html="item.policyData.name"></div>
                <div
                    class="content"
                    v-html="item.policyData.info_content"
                ></div>
                <div class="date">
                    <div>效力注释：{{ item.policyData.active_info }}</div>
                    <div
                        v-html="'发文日期：' + item.policyData.push_date"
                    ></div>
                    <div
                        v-html="'发文字号：' + item.policyData.push_number"
                        style="width: 100%"
                    ></div>
                </div>
            </nuxt-link>
        </div>
        <div class="page">
            <van-pagination
                v-model="page"
                :total-items="total"
                :show-page-size="3"
                :items-per-page="limit"
                force-ellipses
                @change="currentChange"
            />
        </div>

        <van-overlay :show="loading" z-index="999">
            <div class="wrapper" @click.stop>
                <van-loading vertical color="#ffffff">加载中...</van-loading>
            </div>
        </van-overlay>
        <van-popup v-model="showPicker" round position="bottom">
            <van-picker
                show-toolbar
                :columns="columns"
                @cancel="showPicker = false"
                @confirm="onConfirm"
            />
        </van-popup>
        <van-popup v-model="showDate" round position="bottom">
            <van-datetime-picker
                v-model="currentDate"
                type="date"
                title="选择年月日"
                :min-date="minDate"
                :max-date="maxDate"
                @confirm="dateConfirm"
            />
        </van-popup>
    </div>
</template>

<script>
import region from "@/assets/json/region.json";
import { mapMutations, mapState, mapActions } from "vuex";
import { normSearch } from "@/assets/api/searchApi";
import {
    readJsonFileContent,
    getText,
    goTopSmooth,
    answerFormat3,
} from "@/assets/utils/utils";
import { getPolicyCate } from "@/assets/api/regulationsApi.js";
import { getanalysedata } from "@/assets/api/indexApi.js";
var policyDataList = [];
export default {
    name: "QuizDataSearch",
    components: {},
    head() {
        return {
            title: this.mateInfo.title + "搜索结果-【小竹财税平台】",
            meta: [
                {
                    hid: "keywords",
                    name: "keywords",
                    content: "小竹财税,会计法规库",
                },
            ],
        };
    },
    layout: "home",
    data() {
        return {
            input: "",
            mateInfo: {
                title: "",
                keywords: "",
                description: "",
            },

            retrieveFields: "name",

            searchInput: "",
            number2: "",
            number3: "",
            date: "",

            tabsIndex: 0,

            pickerOptions: {
                shortcuts: [
                    {
                        text: "一个月内",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 30
                            );
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "三个月内",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 90
                            );
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "一年内",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 365
                            );
                            picker.$emit("pick", [start, end]);
                        },
                    },
                ],
            },

            limit: 15,
            page: 1,
            total: 0,
            pageDataList: [],

            loading: false,

            queryKeywords: [],

            sortPushDate: null, // 升序：0，降序：1

            filter: null,

            dateFilterate: 0,

            region: [],
            regionProps: {
                label: "name",
                value: "id",
                children: "children",
            }, // 地区级联选择器配置
            city_code: "",
            cityShow: false,

            // 效力注释
            xiaoliList: [
                {
                    id: "现行有效",
                    name: "现行有效",
                },
                {
                    id: "部分失效/废止",
                    name: "部分失效/废止",
                },
                {
                    id: "全文失效/废止",
                    name: "全文失效/废止",
                },
                {
                    id: "已修订",
                    name: "已修订",
                },
            ],
            active_info: 0,

            // 税种
            policyCate: [],
            policyCateIndex: -1,

            showPicker: false,
            columns: [
                { text: "查标题", name: "name" },
                { text: "查文章", name: "info_content_text" },
                { text: "查文号", name: "push_number" },
                { text: "查时间", name: "push_date" },
            ],
            retrieveFields: "name",
            date1: "",
            date2: "",
            dateIndex: 1,
            showDate: false,
            minDate: new Date(1970, 0, 1),
            maxDate: new Date(),
            currentDate: new Date(),
        };
    },
    computed: {
        ...mapState("common", {
            userInfo: (state) => state.userInfo,
        }),
        ...mapState("regulations", {
            tabsList: (state) => state.TTabsList,
        }),

        getCity: function () {
            if (!this.city_code || !this.city_code[0]) {
                return "全部";
            }
            if (this.region.length > 0 && this.city_code.length > 0) {
                for (let items of this.region) {
                    if (items.id == this.city_code[0]) {
                        for (let item of items.children) {
                            if (item.id == this.city_code[1]) {
                                if (items.name == item.name) return items.name;
                                else return items.name + item.name;
                            }
                        }
                    }
                }
            }
        },
    },
    created() {},
    mounted() {
        this.retrieveFields = this.$route.query.t;
        switch (this.$route.query.t) {
            case "name":
                this.searchInput = this.$route.query.k;
                break;
            case "info_content_text":
                this.searchInput = this.$route.query.k;
                break;
            case "push_date":
                this.date = this.$route.query.date.split(",");
                this.date1 = this.date[0];
                this.date2 = this.date[1];
                break;
            case "push_number":
                this.searchInput = this.$route.query.k;
                // this.number2 = this.$route.query.n2;
                // this.number3 = this.$route.query.n3;
                break;
            default:
                this.searchInput = this.$route.query.k;
                this.retrieveFields = "name";
                break;
        }

        this.getRegion();
        // 获取税种
        this.getPolicyCate();
        this.policySearch();
        getanalysedata({
            m_id: 3,
            type: 1,
            code: "PE2",
            describe: this.searchInput,
        });
    },
    watch: {},

    methods: {
        ...mapActions("regulations", ["ASTabList"]),
        searchClick() {
            if (
                this.retrieveFields == "name" ||
                this.retrieveFields == "info_content_text" ||
                this.retrieveFields == "push_number"
            ) {
                if (!this.searchInput) {
                    Toast("请输入搜索内容");
                    return;
                }
            }
            if (this.retrieveFields == "push_date") {
                if (!this.date1 || !this.date2) {
                    Toast("请选择时间范围");
                    return;
                }
            }
            if (this.retrieveFields == "push_date") this.searchInput = "";
            else {
                this.date = "";
                this.date1 = "";
                this.date2 = "";
            }
            this.dateFilterate = 0;
            this.active_info = 0;
            this.policyCateIndex = -1;
            this.mateInfo.title = this.searchInput;
            this.sortPushDate = null;
            this.city_code = "";
            this.page = 1;
            this.$router.push({
                path: "/kjfgksearch",
                query: {
                    k: this.searchInput,
                    date: `${this.date1},${this.date2}`,
                    t: this.retrieveFields,
                },
            });
            this.policySearch();
        },

        async policySearch() {
            if (
                (this.retrieveFields == "name" ||
                    this.retrieveFields == "info_content_text") &&
                !this.searchInput
            ) {
                this.searchInput = this.$route.query.k;
            }
            if (this.retrieveFields == "push_date" && !this.date) {
                this.date = this.$route.query.date.split(",");
            }
            if (this.retrieveFields == "push_number" && !this.searchInput) {
                this.searchInput = this.$route.query.k;
            }

            if (this.loading) return;
            this.loading = true;

            this.mateInfo.title = this.searchInput;
            let keyword = this.searchInput;

            if (this.retrieveFields == "push_number")
                keyword = this.searchInput;

            let params = {
                query: keyword,
                retrieveFields:
                    this.retrieveFields == "info_content_text"
                        ? [this.retrieveFields, "name"]
                        : [this.retrieveFields],
                page: this.page,
                pageSize: this.limit,
                filter: {},
            };

            if (this.sortPushDate !== null) {
                params.sortList = [{ push_date: this.sortPushDate }];
            }

            if (this.date1 && this.date2) {
                params.dateScope = {
                    startDate: this.date1,
                    endDate: this.date2,
                };
            }

            // 判断过滤条件
            if (this.filter) {
                if (!this.filter.code) params.filter = this.filter;
                else params.code = this.filter.code;
            }

            const res = await normSearch(params);
            if (res.status == 0) {
                this.total = res.data.resultTotal;
                this.queryKeywords = res.data.queryKeywords;
                policyDataList = res.data.result;

                this.getPageData();
            }
        },

        // 取到当前分页的数据
        async getPageData() {
            for (let item of policyDataList) {
                let data = await readJsonFileContent(item.matchDataUrl);
                data.data.info_content = getText(data.data.info_content, 120);
                item.policyData = {
                    ...data.data,
                };
            }

            this.pageDataList = answerFormat3(
                policyDataList,
                this.queryKeywords,
                this.retrieveFields
            );
            this.$nextTick(() => {
                this.loading = false;
                goTopSmooth();
            });
        },

        command(e) {
            this.searchInput = "";
            this.date = "";
            this.number2 = "";
            this.number3 = "";
            this.retrieveFields = e;
        },

        // 一级菜单过滤
        tabsFilter(item, index) {
            this.filter = item.searchFilter;
            this.tabsIndex = index;
            this.policySearch();
        },

        // 切换排序
        checkSort() {
            if (this.sortPushDate === null) this.sortPushDate = 1;
            else if (this.sortPushDate === 1) this.sortPushDate = 0;
            else if (this.sortPushDate === 0) this.sortPushDate = null;
            this.page = 1;
            this.policySearch();
        },

        // 选择地区
        cityChange(e) {
            this.cityShow = false;
            this.policySearch();
        },

        // 选择效力注释
        xiaoliChang(e) {
            this.active_info = e;
            this.policySearch();
        },

        currentChange(page) {
            if (this.loading) return;
            this.page = page;
            goTopSmooth();
            this.policySearch();
        },

        checkScreen(fn) {
            this.retrieveFields = fn;
            this.policySearch();
        },

        // 获取税种
        async getPolicyCate() {
            const res = await getPolicyCate({});
            if (res.code == 1) {
                this.policyCate = res.data;
            }
        },

        // 税种选择
        policyCateChang(e) {
            this.policyCateIndex = e;
            this.policySearch();
        },

        // 处理省市区数据
        getRegion() {
            let region_n = region;
            for (let items of region_n) {
                for (let item of items.children) {
                    delete item.children;
                }
            }

            this.region = [
                {
                    id: "",
                    level: 1,
                    name: "全部",
                    pid: "",
                },
                ...region_n,
            ];
        },

        dateCheck(num) {
            if (this.dateFilterate == num) return;
            this.page = 1;
            this.dateFilterate = num;
            if (num == 0) {
                this.date = "";
                this.policySearch();
                return;
            }
            this.date = [
                new Date(new Date().getTime() - num * 24 * 60 * 60 * 1000)
                    .toISOString()
                    .split("T")[0], //一个月前
                new Date().toISOString().split("T")[0], //当前日期
            ];
            this.policySearch();
        },

        keydown(e) {
            if (!e.shiftKey && e.keyCode == 13) {
                e.cancelBubble = true; //ie阻止冒泡行为
                e.stopPropagation(); //Firefox阻止冒泡行为
                e.preventDefault(); //取消事件的默认动作*换行
                //以下处理发送消息代码
                if (e.keyCode == 13) {
                    this.searchClick();
                }
            }
        },

        showDatePopup(index) {
            this.dateIndex = index;
            this.showDate = true;
        },

        dateConfirm(date) {
            let year = date.getFullYear(); // 获取年份（四位数）
            let month = ("0" + (date.getMonth() + 1)).slice(-2); // 获取月份（注意月份是从0开始的，所以需要+1），并确保是两位数
            let day = ("0" + date.getDate()).slice(-2);
            let formattedDate = year + "-" + month + "-" + day;
            this["date" + this.dateIndex] = formattedDate;
            this.showDate = false;
        },
        onConfirm(item, index) {
            this.retrieveFields = item.name;
            this.showPicker = false;
        },
    },
};
</script>

<style lang="scss" scoped>
.search {
    position: relative;
    z-index: 10;
    width: 91%;
    height: 2.5rem;
    margin: 1rem auto 0.8rem;
    background-color: #f4f5f9;
    border-radius: 2.5rem;
    display: flex;
    align-items: center;
    padding: 0 1rem 0 1.2rem;
    .select {
        font-size: 0.75rem;
        color: #333333;
        .select-icon {
            transform: rotate(90deg);
            position: relative;
            top: -0.07rem;
        }
    }
    .line {
        width: 1px;
        height: 1.125rem;
        background-color: #bbbbbb;
        margin: 0 0.68rem;
    }
    .input {
        width: 63%;
    }
    .search-icon {
        position: absolute;
        right: 1rem;
    }

    .input-date {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        font-size: 0.75rem;
        div {
            width: 100%;
            text-align: center;
            height: 1.2rem;
            line-height: 1.2rem;
        }
        span {
            color: #999999;
        }
    }

    ::v-deep .van-cell {
        padding: 0;
    }
    ::v-deep .van-search {
        padding: 0;
    }
    ::v-deep .van-search__content {
        background: #f4f5f9;
    }
    ::v-deep .van-field__left-icon {
        display: none;
    }
}

.data-list {
    background-color: #f6f6f6;
    padding: 0 0.9rem;
    min-height: 100vh;
    .total {
        color: #666666;
        font-size: 0.75rem;
        padding: 0.4rem 0;
    }
}

.data-item {
    display: block;
    background-color: #ffffff;
    padding: 0.5rem 0.6rem;
    margin-bottom: 0.6rem;
    border-radius: 0.2rem;
    .title {
        color: #3d3d3d;
        font-size: 1.1rem;
        margin-bottom: 0.35rem;
    }
    .content {
        font-size: 0.75rem;
        color: #999999;
    }
    .date {
        margin-top: 0.35rem;
        color: #999999;
        font-size: 0.68rem;
        display: flex;
        flex-wrap: wrap;
        > div {
            width: 50%;
        }
    }
    > div {
        white-space: nowrap; /* 不换行 */
        overflow: hidden; /* 超出部分隐藏 */
        text-overflow: ellipsis; /* 超出部分显示省略号 */
        -webkit-line-clamp: 2; /* 限定显示的行数，这里设置为3行 */
        -webkit-box-orient: vertical; /* 这使得display:-webkit-box生效 */
        display: -webkit-box; /* 作为flex容器的webkit版本 */
        white-space: normal;
        line-height: 1.5;
    }
}

.page {
    padding: 1rem 0;
}

.wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}
</style>
